<?php

class Server
{
    private $server;
    private $host = '127.0.0.1';
    private $port = '8899';
    private $path = '/service';

    public function __construct()
    {
        $this->server = stream_socket_server("tcp://{$this->host}:{$this->port}",$errno,$errstr);
        if(!$this->server) exit("{$errno}:{$errstr}".PHP_EOL);

        $dir = realpath(__DIR__.$this->path);
        if($dir === false || !file_exists($dir)) exit("路径错误:{$this->path}".PHP_EOL);


        while($this->server){
            $client = stream_socket_accept($this->server);

            if($client){
                //读取并解析数据
                $buf = fread($client, 2048);
                $buf = json_decode($buf, true);
                $class = $buf['class'];
                $method = $buf['method'];
                $params = $buf['params'];

                //调用服务文件
                if ($class && $method) {
                    $file = $dir . '/' . $class . '.php';
                    if (file_exists($file)) {
                        require_once $file;
                        $obj = new $class();
                        //如果有参数，则传入指定参数
                        if (!$params) {
                            $data = $obj->$method();
                        } else {
                            $data = $obj->$method($params);
                        }
                        //返回结果
                        fwrite($client, $data);
                    }else{
                        fwrite($client,date('Y-m-d H:i:s')."\t"."[$file] Service files do not exist.");
                    }
                } else {
                    fwrite($client, 'class or method error');
                }
                //关闭客户端
                fclose($client);
            }
        }
    }

    public function __destruct() {
        fclose($this->server);
    }
}
new Server();